<?php

namespace app\index\controller;

use app\BaseController;
use app\index\model\Msg;
use app\index\model\User as ModelUser;
use app\index\validate\User;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;

class Register extends BaseController
{

    public function index()
    {
        $this->logs('注册视图');
        return view();
    }
    public function doReg()
    {
        $this->logs('注册');
        if (!config('system.switch.register')) return error('当前站点已关闭登录');
        $param = input();
        $param['usernameReg'] = $param['username'];
        $param['passwordReg'] = $param['password'];
        $ip = request()->ip();
        try {
            validate(User::class)->scene('register')->check($param);
            if (!captcha_check($param['captcha']))  return error('验证码错误');
            $ipBan = ModelUser::where(['ip' => $ip, 'status' => 0])->findOrEmpty()->isEmpty();
            if (!$ipBan) return error('当前IP被封禁，如有需要，请联系管理解封');
            $userData = Db::name('user')->where('username', $param['username'])->find();
            if ($userData) return error('该用户名已存在，请更换另一个吧！');
            $hasEmail = Db::name('user')->where('email', $param['email'])->find();
            if (!empty(@$hasEmail)) return error('该邮箱已被注册');
            $data = [
                'username' => $param['username'],
                'password' => md5(config('secure.secret_key') . $param['password']),
                'nickname' => @$param['nickname'] ?? randStr(5) . substr(time() , 6 ,9) . random_int(0 , 10),
                'email' => $param['email'],
                'head_icon' => '/static/images/headIcon/default.jpeg',
                'status' => config('system.switch.reg_examine') ==  1 ? 2 : 1,
                'ip' => $ip,
            ];
            $res = ModelUser::create($data);
            if ($res) {
                $msg = '欢迎加入到' . config('system.base.title') . '！您已成功注册，期待您在这里分享见解，交流心得，开启精彩讨论之旅！';
                Msg::send(0, $res->id, ['content' => $msg]);
                return success();
            }
            return error('注册失败');
        } catch (ValidateException  $e) {
            return error($e->getMessage());
        }
    }
}
